
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ScrewTurn.Wiki.PluginFramework;
using System.Text;

namespace ScrewTurn.Wiki {

	public partial class Diff : BasePage {

		protected void Page_Load(object sender, EventArgs e) {
			Page.Title = Resources.Messages.DiffTitle + " - " + Settings.WikiTitle;

			PrintDiff();
		}

		public void PrintDiff() {
			if(Request["Page"] == null || Request["Rev1"] == null || Request["Rev2"] == null) {
				Redirect();
				return;
			}

			StringBuilder sb = new StringBuilder();

			PageInfo page = Pages.Instance.FindPage(Request["Page"]);
			if(page == null) {
				Redirect();
				return;
			}

			int rev1 = -1, rev2 = -1;
			try {
				rev1 = int.Parse(Request["Rev1"]);
				rev2 = int.Parse(Request["Rev2"]);
			}
			catch { }
			if(rev1 == -1 || (rev2 == -1 && !Request["Rev2"].ToLowerInvariant().Equals("current"))) {
				Redirect();
				return;
			}

			PageContent content = Content.GetPageContent(page, true);

			sb.Append(@"<h1 class=""pagetitle"">");
			sb.Append(Resources.Messages.DiffingPage.Replace("##PAGETITLE##", content.Title).Replace("##REV1##", rev1.ToString()).Replace("##REV2##", (rev2 != -1 ? rev2.ToString() : Resources.Messages.Current)));
			sb.Append("</h1>");

			sb.Append(@"<br /><table style=""padding: 0px;"" class=""box""><tr><td><p><b><a href=""History.aspx?Page=");
			sb.Append(Tools.UrlEncode(Request["Page"]));
			sb.Append("&amp;Rev1=");
			sb.Append(Request["Rev1"]);
			sb.Append("&amp;Rev2=");
			sb.Append(Request["Rev2"]);
			sb.Append(@""">&laquo; ");
			sb.Append(Resources.Messages.BackToHistory);
			sb.Append("</a></b> - ");
			sb.Append(Resources.Messages.DiffColorKey);
			sb.Append("</p></td></tr></table><br />");

			PageContent rev1Content = Pages.Instance.GetBackupContent(page, rev1);
			PageContent rev2Content = null;
			if(rev2 != -1) {
				rev2Content = Pages.Instance.GetBackupContent(page, rev2);
			}
			else {
				rev2Content = content;
			}

			string result = DiffTools.DiffRevisions(rev1Content.Content, rev2Content.Content);

			sb.Append(result);

			lblDiff.Text = sb.ToString();
		}

		private void Redirect() {
			Response.Redirect(Settings.DefaultPage + Settings.PageExtension);
		}

	}

}
